from django import http
from django.contrib.auth import mixins
from django.contrib.auth.backends import ModelBackend
import re
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings

from django.views import View

from users.models import User


def get_user_by_account(account):
    """
    通过传入用户名,或手机号动态查询user
    :param account: username 或 mobile
    :return: user or  None
    """
    try:
        if re.match(r'^1[3-9]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None
    else:
        return user


class UsernameMobileAuthBackend(ModelBackend):
    """自定久登录认证后端类"""

    def authenticate(self, request, username=None, password=None, **kwargs):

        # 1.查询user (可以通过用户名或手机号动态查询user)
        user = get_user_by_account(username)
        # 2.校验密码是否正确
        if user and user.check_password(password):
            # 3.返回user或None
            return user




def EncodeEmailUrl(user):
    """ 传入user对象，返回一个url"""
    data = {"user_id":user.id,"email":user.email}
    serializer = Serializer(settings.SECRET_KEY,600)
    token = serializer.dumps(data).decode()
    verify_url = settings.EMAIL_VERIFY_URL + '?token=' + token
    return verify_url

def DecodeEmailUrl(url):
    """ 输入一个查询字符串，返回一个user对象"""
    try:
        serializer = Serializer(settings.SECRET_KEY, 600)
        data = serializer.loads(url)
        user_id = data.get("user_id",None)
        email = data.get("email",None)
        user = User.objects.filter(id=user_id, email=email)
        return user
    except:
        return None






# def
EMAIL_HOST = 'smtp.163.com'  # 发邮件主机
EMAIL_HOST_USER = 'itcast99@163.com'  # 授权的邮箱
EMAIL_HOST_PASSWORD = 'python99'  # 邮箱授权时获得的密码，非注册登录密码
EMAIL_FROM = '美多商城<itcast99@163.com>'  # 发件人抬头